/**
 * @ProjectName: 
 * @Copyright: 2014 lisheng  All Right Reserved.
 * @address: toughheart@163.com
 * @date: 2016年3月2日 下午1:36:28
 * @Description: 本内容未经本人允许禁止使用、转发.
 */

package com.ls.fw.web.core.servlet.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

/**
 * 
 * @author lisheng
 * @date 2016年3月2日 下午1:36:28
 * @version V1.0
 */
public class JsonUtils {

	/**
	 * 发送一个键值对json数据到页面
	 * 
	 * @author Defender 2013-7-1 下午09:13:29
	 * @param objName
	 * @param obj
	 * @return void
	 */
	public static String sendJsonData(final HttpServletResponse response,
			final String objName, final Object obj) {
		JSONObject jsonObj = new JSONObject();
		if(obj instanceof Map){
			jsonObj.putAll((Map)obj);
		}else{
			jsonObj.put(objName, obj);
		}
		return sendJsonData(response, jsonObj);
	}
	

	/**
	 * 发送json数据到页面
	 * 
	 * @author Defender 2013-7-1 下午09:12:17
	 * @param jsonObj
	 * @return void
	 */
	public static String sendJsonData(final HttpServletResponse response,
			final JSONObject jsonObj) {
		String msg = jsonObj.toString();
		return sendJsonData(response, msg);
	}
	
	public static String sendJsonData(final HttpServletResponse response,
			final String msg) {
		String encoding = "UTF-8";
		String contentType = "application/json";
		contentType = contentType + ";charset=" + encoding;
		response.setContentType(contentType);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
			pw.write(msg);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return msg;
	}
}
